import time
from celery import shared_task
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from index.basic_db_ops import write_inverter_second_data1
from index.db_Session import get_db_session


# 这是一次异步的测试
@shared_task(time_limit=60)  # 设置任务超时时间为 60 秒
def demo_loop():
    cnt = 0
    try:
        while True:
            cnt += 1
            time.sleep(3)
            print(f"3秒过去了, {cnt}")
    except Exception as e:
        print(f"任务执行出错: {e}")


@shared_task
def write_pv_data_task():
    # postgres_user_name = "postgres"
    # password = "123456"
    # db_name = "system_database"
    # engine = create_engine(f'postgresql://{postgres_user_name}:{password}@localhost:5432/{db_name}')
    # Session = sessionmaker(bind=engine)  # 生成 Session 类
    Session = get_db_session()
    # 控制循环的开关
    running = True
    try:
        while running:
            # 记录本次循环开始时间
            start_time = time.time()
            # 调用你的函数
            write_inverter_second_data1(Session, 1)
            # 计算剩余等待时间（1秒 - 函数执行时间）
            elapsed = time.time() - start_time
            sleep_time = max(0.0, 1.0 - elapsed)  # 避免负数
            # 精确等待剩余时间
            time.sleep(sleep_time)
    except KeyboardInterrupt:
        print("\n循环已手动停止")
        running = False
    except Exception as e:
        print(f"任务执行出错: {e}")